layui.use(['form', 'admin', 'ax', 'table', 'treetable', 'laytpl'], function () {
    var $ax = layui.ax;
    var admin = layui.admin;
    var table = layui.table;
    var treetable = layui.treetable;
    var form = layui.form;
    var laytpl = layui.laytpl;

    var Current = {
        tableId: "table"
    };

    var needToken = null;
    form.on('checkbox(needToken)', function (data) {
        if (data.elem.checked) {
            needToken = 1;
        } else {
            needToken = null;
        }
    });

    form.on('submit(btnSubmit)', function (data) {
        data.field.needToken = needToken;
        table.reload(Current.tableId, {where: data.field});
        return false;
    });

    //获取所有可筛选服务
    var ajax = new $ax(system.contextPath + "/api/registry.service.lists");
    ajax.setType("get");
    var result = ajax.start();
    if (result.status) {
        var data = result.data;
        var list = [];
        for (var i = 0; i < data.length; i++) {
            var param = {};
            param['name'] = data[i];
            list.push(param);
        }
        var data0 = {
            list: list,
        };
        var part0Temp = document.getElementById('part0-template');
        laytpl(part0Temp.innerHTML).render(data0, function (html) {
            document.getElementById('part0').innerHTML = html;
            form.render();
        });
    }

    Current.initColumn = function () {
        return [[
            {type: 'numbers'},
            {field: 'id', hide: true, sort: true, title: 'id'},
            {field: 'serviceId', sort: false, title: '服务名称'},
            {
                field: 'name', sort: false, title: '接口名(版本号)', templet: function (d) {
                    return d.name + '(' + d.version + ')';
                }
            },
            {
                field: 'roles', sort: false, title: '访问权限', templet: function (d) {
                    var roles = d.roles;
                    var roleArr = [];
                    for (var i = 0; i < roles.length; i++) {
                        roleArr.push(roles[i].description);
                    }
                    var id = d.id;
                    return '<span style="color: #1E9FFF;cursor: pointer;" onclick="onShow(\'' + id + '\')">' + roleArr.join(",") + '</span>';
                }
            },
            {field: 'ignoreValidate', sort: false, title: '签名校验', toolbar: '#validateTpl'},
            {field: 'mergeResult', sort: false, title: '统一输出格式', toolbar: '#mergeTpl'},
            {field: 'needToken', sort: false, title: '需要token', toolbar: '#tokenTpl'},
            {field: 'status', sort: false, title: '状态', toolbar: '#statusTpl'}
        ]];
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Current.tableId,
        url: system.contextPath + '/api/route.page',
        page: true,
        request: {
            pageName: 'pageIndex' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        height: "full-158",
        cellMinWidth: 100,
        cols: Current.initColumn(),
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            };
        }
        , response: {
            statusCode: 200
        }
        , size: 'lg',
        done: function (res, curr, count) {
            count || this.elem.next('.layui-table-view').find('.layui-table-header').css('overflow', 'visible');
            $('.layui-table-body').find('div.layui-table-cell').find('select').each(function () {
                var $this = $(this);
                var val = $this.data('value');
                var text;
                $(this).children().each(function () {
                    if (val == this.value) {
                        text = this.text;
                        return;
                    }
                })
                //更新layui 选择器输入框的值
                $this.next().find('.layui-select-title').find('input').val(text);
                //更新layui 选择器的值 以及设置其样式
                $this.val(val).parents('div.layui-table-cell').css('overflow', 'visible');
            })
            form.render(null, 'table');
        }
    });


    window.onShow = function (routeId) {
        var currRoleArr = [];
        var ajaxR = new $ax(system.contextPath + "/api/route.role.get");
        ajaxR.setType("get");
        ajaxR.set({id: routeId});
        var resultR = ajaxR.start();
        if (resultR.status) {
            currRoleArr = resultR.data;
        }

        //获取所有的应用角色
        var part0Data = [];
        var ajax = new $ax(system.contextPath + "/api/role.listall");
        ajax.setType("get");
        var result = ajax.start();
        if (result.status) {
            part0Data = result.data;
            for (var i = 0; i < part0Data.length; i++) {
                var p = part0Data[i].roleCode;
                for (var j = 0; j < currRoleArr.length; j++) {
                    var c = currRoleArr[j].roleCode;
                    if (c === p) {
                        part0Data[i].checked = true;
                        break;
                    }
                }
            }
        }


        var data0 = {
            list: part0Data,
            routeId: routeId
        };
        var part0Temp = document.getElementById('part1-template');
        laytpl(part0Temp.innerHTML).render(data0, function (html) {
            layer.open({
                btn: ['保存', '取消'],
                area: '30%',
                title: '',
                content: html,
                yes: function (index, layero) {
                    var arr = [];
                    $("input:checkbox[name='roleCode']:checked").each(function (i) {
                        var v = $(this).val();
                        if (v != "{{item.roleCode}}") {
                            arr.push($(this).val());
                        }
                    });
                    var ajax = new $ax(system.contextPath + "/api/route.role.update");
                    ajax.set({routeId: routeId, roleCode: arr.join(",")});
                    var result = ajax.start();
                    if (result.status) {
                        system.success("操作成功");
                        layer.close(index);
                        table.reload(Current.tableId);
                    }
                }, btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });

        form.render();
    }

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Current.onAdd();
    });

    // 监听修改update到表格中
    form.on('select(statusFilter)', function (data) {
        var id = $(data.elem).attr("data-id");
        var status = data.value;
        var param = buildUpdateData(id, 'status', status)
        updateBatchById(param)
    });

    function buildUpdateData(currentId, filed, filedValue) {
        var data = {'id': currentId};
        data[filed] = filedValue;
        return data;
    }

    function updateBatchById(data) {
        var ajax = new $ax(system.contextPath + "/api/route.status.update", function (res) {
            if (res.status) {
                system.success("修改成功！");
                //重新加载表格
                table.reload(Current.tableId)
            } else {
                system.error("失败：" + res.msg);
            }
        }, function (res) {
            system.error("失败：" + res.msg);
        });
        ajax.set(data);
        ajax.start();
    }
});
